<template>
  <div class="cus_table">
    <div class="thead">
      <div class="tr">
        <div
          class="th"
          :style="header.style"
          v-for="header in headers"
          :key="header.key"
        >
          {{ header.label }}
        </div>
      </div>
    </div>
    <div class="tbody">
      <div class="tr" v-for="(item, index) in items" :key="index">
        <div class="td" v-for="header in headers" :key="header.key" :style="header.style">
          <component
            v-if="header.tdcomponentsName"
            :is="header.tdcomponentsName"
            :header="header"
            :item="item"
            :value="item[header.key]"
            v-bind="$attrs"
            v-on="$listeners"
            :style="item['_style']"
          ></component>
          <div v-else>
            {{ item[header.key] }}
          </div>
        </div>
      </div>
    </div>
    <div v-if="items.length === 0" class="no-data">{{ nodata }}</div>
  </div>
</template>
<script>
import { defineComponent } from 'vue'

const customTableComponents = {}
const tdComponents = import.meta.globEager('./td/*.vue')
Object.entries(tdComponents).forEach(([path, component]) => {
  customTableComponents[component.default.name] = component.default
})

export default defineComponent({
  components: customTableComponents,
  name: 'VueTable',
  props: {
    headers: {
      type: Array,
      required: true,
    },
    items: {
      type: Array,
      required: true,
    },
    nodata: {
      type: String,
      default: 'No data available',
    },
  },
})
</script>

<style scoped lang="scss">
.cus_table {
  display: flex;
  flex-direction: column;
  border: 0.5px solid black;
  .thead {
    display: flex;
    flex-direction: column;

    .tr {
      display: flex;

      .th {
        border: 0.5px solid black;
        flex: 1;
      }
    }
  }

  .tbody {
    display: flex;
    flex-direction: column;

    .tr {
      display: flex;

      .td {
        border: 0.5px solid black;
        flex: 1;
      }
    }
  }

  .no-data {
    margin-top: 8px;
    text-align: center;
  }
}
</style>